<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Request;


class User extends Model
{
    //signUp
    public function signUp()
    {
        $has_username_password = $this->has_username_password();
        if (!$has_username_password)
            return err('用户名密码皆不能为空');
        $username = $has_username_password[0];
        $password = $has_username_password[1];
        //check repeat

        $user_exists = $this
            ->where('username', $username)
            ->exists();

        if ($user_exists)
            return err('用户名已存在');
        //Encrypted password
        $password = bcrypt($password);

        //insert
        $user = $this;
        $user->username = $username;
        $user->password = $password;
        if ($user->save())
            return suc(['id' => $user->id]);
        else
            return err('insert fail');
    }

    //获取信息
    public function read()
    {
        if (!rq('id'))
            return err('id required');

        $id = rq('id');
        if (rq('id') === 'self') {
            if (!$this->is_logged_in())
                return err('login required');
            $id = session('user_id');
        }


        $get = ['id', 'username', 'avatar_url', 'intro'];
        $user = $this->find($id, $get);

        if (!$user)
            return err('user exists');
        $data = $user->toArray();

        $answer_count = $user->answers()->count();
        //$answer_count = answer_ins()->where(['user_id' => $id])->count();
        $question_count = question_ins()->where(['user_id' => $id])->count();
        $data['answer_count'] = $answer_count;
        $data['question_count'] = $question_count;

        return suc(['data' => $data]);
    }

    //login
    public function login()
    {
        $has_username_password = $this->has_username_password();
        if (!$has_username_password)
            return err('用户名密码皆不能为空');
        $username = $has_username_password[0];
        $password = $has_username_password[1];
        //check username
        $user = $this->where('username', $username)->first();

        if (empty($user))
            return err('用户不存在');
        //check password
        if (!Hash::check($password, $user->password))
            return err('password error');

        //session put
        session()->put('username', $user->username);
        session()->put('user_id', $user->id);

        return suc();
    }

    //loginOut
    public function logOut()
    {
        //session()->flush();
        //session 可以嵌套  session()->put('username.age', 23);
        session()->forget('username');
        session()->forget('user_id');
        return suc();
        //return redirect('/');
    }

    //username exists
    public function exist()
    {
        if (empty(rq('username')))
            return err('username required');
        $count = $this->where(['username' => rq('username')])->count();
        if ($count)
            return err('username has exists');
        return suc();
    }


    public function has_username_password()
    {
        $username = Request::get('username');
        $password = Request::get('password');
        //check empty
        if ($username && $password)
            return [$username, $password];
        else
            return false;
    }

    public function is_logged_in()
    {
        return is_logged_in();
    }

    //修改密码
    public function change_password()
    {
        if (!user_ins()->is_logged_in())
            return err('no login');

        if (!rq('old_password') || !rq('new_password'))

            return err('old_password&new_password required');

        $user = $this->find(session('user_id'));
        if (!Hash::check(rq('old_password'), $user->password))
            return err('old_password error');

        $user->password = bcrypt(rq('new_password'));
        return $user->save() ? suc() : err('save failed');

    }

    //忘记密码
    public function reset_password()
    {
        if (!rq('phone'))
            return err('phone required');
        $user = $this->where('phone', rq('phone'))->first();

        if (!$user)
            return err('phone error');

        if ($this->is_robot())
            return err('busy');

        //验证码
        $captcha = $this->generate_captcha();
        $user->phone_captcha = $captcha;
        //发送验证码 todo
        $this->update_robot_time();
        return $user->save() ? suc() : err('save  fail');

    }

    //生成验证码
    public function generate_captcha()
    {
        return rand(100000, 999999);
    }

    //验证captcha
    public function validate_reset_password()
    {
        if (!rq('phone') || !rq('phone_captcha') || !rq('new_password'))
            return err('phone&phone_captcha&new_password required');
        $user = $this->where([
            'phone' => rq('phone'),
            'phone_captcha' => rq('phone_captcha')
        ])->first();

        if ($this->is_robot(3))
            return err('busy');

        if (!$user)
            return err('invalid phone or phone_captcha');

        $user->password = bcrypt(rq('new_password'));
        $this->update_robot_time();
        return $user->save() ? suc() : err('save  fail');
    }

    public function is_robot($time = 10)
    {
        if (!session()->get('last_action_time'))
            return false;
        //防止频繁调用
        $current_time = time();
        $last_sms_time = session()->get('last_action_time');

        return ($current_time - $last_sms_time < $time);
    }

    public function update_robot_time()
    {
        session()->set('last_action_time', time());
    }

    public function answers()
    {
        return $this->belongsToMany('App\Answer')
            ->withPivot('vote')
            ->withTimestamps();
    }

}
